# cython: language_level=3
import os
import aioredis

class RedisClient:
    def __init__(self, redis_url=None):
        REDIS_HOST=os.getenv("REDIS_HOST", "localhost")
        REDIS_PORT=os.getenv("REDIS_PORT", 6379)
        REDIS_URL = "redis://" + REDIS_HOST + ":" + REDIS_PORT
        self.redis_url = redis_url if redis_url != None else REDIS_URL
        self.redis_pool = None

    async def connect(self):
        REDIS_HOST=os.getenv("REDIS_HOST", "localhost")
        REDIS_PORT=os.getenv("REDIS_PORT", 6379)
        REDIS_PASSWORD=os.getenv("REDIS_PASSWORD")
        REDIS_DB=os.getenv("REDIS_DB")
        REDIS_PREFIX=os.getenv("REDIS_PREFIX")
        REDIS_URL = "redis://" + REDIS_HOST + ":" + REDIS_PORT
        if self.redis_pool is None:
            self.redis_pool = await aioredis.from_url(
                REDIS_URL,
                password=REDIS_PASSWORD,
                encoding="utf-8",
                decode_responses=True
            )

    async def disconnect(self):
        if self.redis_pool is not None:
            await self.redis_pool.close()
            await self.redis_pool.wait_closed()
            self.redis_pool = None

    async def get(self, key):
        return await self.redis_pool.get(key)

    async def set(self, key, value):
        await self.redis_pool.set(key, value)

    async def incrby(self, key, increment):
        return await self.redis_pool.incrby(key, increment)